/*
 *             Copyright (C) 2024 Steve Jrong
 *
 * 	   GitHub Homepage: https://www.github.com/SteveJrong
 *      Gitee Homepage: https://gitee.com/stevejrong1024
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.stevejrong.waiter.common.component.util;

import com.stevejrong.waiter.common.component.BaseConstants;

import lombok.NoArgsConstructor;

import java.sql.Timestamp;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 工具类 - 时间日期
 *
 * @author Steve Jrong
 * @since 1.0
 */
@NoArgsConstructor
public final class DateTimeUtil {

    /**
     * 默认以中国时区，获取带时区的、当前的日期时间
     *
     * @return 带时区的、当前的日期时间
     */
    private static ZonedDateTime getZonedDateTimeByNow() {
        return LocalDateTime.now()
                .atZone(ZoneId.of(BaseConstants.DateTimeConstants.UTC_GMT8_ZONE_ID.desc()));
    }

    /**
     * 将java.util.Data对象，带自定义时区转换为java.time.LocalDateTime对象
     * <p>
     * 私有方法，仅限内部便利使用
     *
     * @param date   java.util.Data对象
     * @param zoneId 自定义的时区编号
     * @return java.time.LocalDateTime对象
     */
    private static LocalDateTime dateToLocalDateTime(Date date, String zoneId) {
        Instant instant = date.toInstant();
        return instant.atZone(ZoneId.of(zoneId)).toLocalDateTime();
    }

    /**
     * 默认以中国时区，获取当前日期时间
     *
     * @return java.time.LocalDateTime对象
     */
    public static LocalDateTime getLocalDateTimeByNow() {
        return getZonedDateTimeByNow().toLocalDateTime();
    }

    /**
     * 默认以中国时区，获取当前日期
     *
     * @return java.time.LocalDateTime对象
     */
    public static LocalDate getLocalDateByNow() {
        return getZonedDateTimeByNow().toLocalDate();
    }

    /**
     * 默认以中国时区，获取当前日期时间
     *
     * @return java.util.Data对象
     */
    public static Date getDateByNow() {
        return Date.from(getZonedDateTimeByNow().toInstant());
    }

    /**
     * 默认以中国时区，获取当前时间戳
     *
     * @return 长整型时间戳
     */
    public static long getTimestampByNow() {
        return Timestamp.valueOf(getLocalDateTimeByNow()).getTime();
    }

    /**
     * 格式化java.util.Data对象，为时间日期字符串
     *
     * @param datePattern 时间日期格式
     * @param zoneId      时区编号
     * @param date        待格式化的java.util.Data对象
     * @return 时间日期字符串
     */
    public static String formatDate(String datePattern, String zoneId, Date date) {
        return DateTimeFormatter.ofPattern(datePattern)
                .format(dateToLocalDateTime(date, zoneId));
    }
}